import router from './index'
import store from '@/store'
import { menuTree } from '@/api/menu'
import { getAccessToken } from '@/utils/auth'
import { filterAsyncRouter } from '@/store/modules/permission'

// NProgress 进度条的使用
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const statue = {
    path: '*',
    component: () => import('@/views/components/Err404.vue'), hidden: true
}

router.beforeEach(async(to, from, next) => {
    console.log(".........测试路由1.........");
    // 开始进度条
    NProgress.start()
    if(to.path !== '/login'){
        let accessToken = getAccessToken();
        if (accessToken) {

            // 动态路由，拉取菜单
            loadMenus(next, to)

            next()
            NProgress.done()
        }else {
            next(`/login`)
            NProgress.done()
        }
    }else {
        next()
        NProgress.done()
    }
})

router.afterEach(() => {
    // 完成进度条
    NProgress.done()
})

export const loadMenus = (next, to) => {
    menuTree().then(res => {
        console.log("菜单树：", res.result);
        const asyncRouter = filterAsyncRouter(res.result)
        asyncRouter.push(statue)
        store.dispatch('permission/generateRoutes', asyncRouter).then(() => { // 存储路由

            console.log("asyncRouter = ",asyncRouter);

            // let home = {
            //     path: "/home",
            //     name: "home",
            //     component: () => import('../views/Home'),
            //     children: asyncRouter
            // }
            // console.log("home ",home);


            // 动态添加可访问路由表
            router.addRoutes(asyncRouter)
        })
        next({ ...to, replace: true })
    })
}

